package com.thinkit.bigdata.core.util.httpUtil;

import org.apache.log4j.Logger;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * Created by thinkit on 2017/2/21.
 */
public class HttpUtil {

    private static Logger logger = Logger.getLogger(HttpUtil.class);


    /**
     * 转换请求为 String
     *
     * @param request -
     * @return String
     * @throws IOException -
     */
    public static String getStringArray(HttpServletRequest request) throws IOException {
        String acceptJsonArray;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), StandardCharsets.UTF_8));

        StringBuilder sb = new StringBuilder("");
        String temp;
        while ((temp = bufferedReader.readLine()) != null) {
            sb.append(temp);
        }
        bufferedReader.close();
        acceptJsonArray = sb.toString();
        return acceptJsonArray;
    }


    /**
     * 发送请求
     *
     * @param url -
     * @param postParam -
     * @param contentType -
     * @param charset -
     * @return -
     */
    private static String send(String url, String postParam, String contentType, String charset) throws IOException {
        OutputStream osw;
        InputStream ins;
        HttpURLConnection con = (HttpURLConnection) (new URL(url)).openConnection();
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setConnectTimeout(10000);
        con.setReadTimeout(600000);
        con.setRequestProperty("Content-Type", contentType);
        con.setDoOutput(true);
        byte[] resCode = postParam.getBytes(StandardCharsets.UTF_8);
        con.setRequestProperty("Content-Length", Integer.toString(resCode.length));
        osw = con.getOutputStream();
        osw.write(resCode);
        osw.flush();
        int resCode1 = con.getResponseCode();
        if (resCode1 < 400) {
            ins = con.getInputStream();
        } else {
            ins = con.getErrorStream();
        }
        String var7 = readContent(ins, charset);
        if (osw != null) {
            osw.close();
        }
        if (ins != null) {
            ins.close();
        }
        return var7;
    }

    /**
     * 发送请求
     *
     * @param url -
     * @param postParam -
     * @param contentType -
     * @param charset -
     * @return -
     */
    private static Map<String, String> send_returnMap(String url, String postParam, String contentType, String charset) {
        OutputStream osw = null;
        InputStream ins = null;
        String var7 = null;
        Map<String, String> res = new HashMap<>();
        res.put("responseCode", "400");
        try {
            HttpURLConnection con = (HttpURLConnection) (new URL(url)).openConnection();
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setConnectTimeout(10000);
            con.setReadTimeout(600000);
            con.setRequestProperty("Content-Type", contentType);
            if (null != postParam) {
                con.setDoOutput(true);
                byte[] resCode = postParam.getBytes(StandardCharsets.UTF_8);
                con.setRequestProperty("Content-Length", Integer.toString(resCode.length));
                osw = con.getOutputStream();
                osw.write(resCode);
                osw.flush();
            }

            int resCode1 = con.getResponseCode();
            res.put("responseCode", resCode1 + "");
            if (resCode1 < 400) {
                ins = con.getInputStream();
            } else {
                ins = con.getErrorStream();
            }

            var7 = readContent(ins, charset);
        } catch (Exception e) {
            logger.info("请求发送失败！");
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException e) {
                logger.info(Arrays.toString(e.getStackTrace()));
            }
        }
        res.put("responseContent", var7);
        return res;
    }


    private static String readContent(InputStream ins, String charset) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(ins, charset));

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    }


    /**
     * 发送Post请求
     * 数据格式为 json
     *
     * @param url -
     * @return -
     */
    public static String sendJsonHttpPost(String url, String json) throws IOException {
        logger.info("【下发Http请求】url=" + url);
        String charset = "UTF-8";
        return send(url, json, "application/json", charset);
    }


    /**
     * 添加get方法
     *
     * @param id -
     * @return -
     * @throws IOException -
     */
    public static String getOne(String esQueryUrl, String id) throws IOException {
        return get(esQueryUrl + id + "/?pretty", "UTF-8");
    }

    public static String sendGetTaskStart(String url) throws IOException {
        return get(url, "UTF-8");
    }

    /**
     * 添加get方法
     *
     * @param url -
     * @param charset -
     * @return -
     * @throws IOException -
     */
    public static String get(String url, String charset) throws IOException {
        logger.info("request:url:" + url);
        InputStream ins = null;

        String var5;
        try {
            HttpURLConnection con = (HttpURLConnection) (new URL(url)).openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(10000);
            con.setReadTimeout(600000);
            int resCode = con.getResponseCode();
            if (resCode < 400) {
                ins = con.getInputStream();
            } else {
                ins = con.getErrorStream();
            }

            var5 = readContent(ins, charset);
        } finally {
            if (ins != null) {
                ins.close();
            }

        }

        return var5;
    }


}
